package net.chowda.appinject.model;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AppConfigManager {
    public static synchronized List<AppConfig> getAppConfigs() {
        List<AppConfig> configs = new ArrayList<AppConfig>();
        try {
            List apps = XPath.selectNodes(getDOM(), "//app");
            for (Object app : apps) {
                configs.add(appElementToObject((Element) app));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configs;
    }

    public static synchronized AppConfig getAppConfig(String name) {
        AppConfig appConfig = new AppConfig();
        try {
            Element app = (Element) XPath.selectSingleNode(getDOM(), "//app[name = '"+name+"']");
            appConfig = appElementToObject(app);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return appConfig;
    }

    private static AppConfig appElementToObject(Element element) {
        Element nameElement = element.getChild("name");
        Element descElement = element.getChild("description");
        Element urlElement  = element.getChild("url");
        Element jsElement   = element.getChild("inline-js");
        List<Element> ijsElement  = element.getChildren("injectjs");
        Element ovlyElement = element.getChild("overlay");
        Element dnElement = element.getChild("display-name");

        AppConfig appConfig = new AppConfig();
        appConfig.setName(nameElement.getTextTrim());
        if(urlElement != null) {
            appConfig.setUrl(urlElement.getTextTrim());
            appConfig.setRedirect("true".equals(urlElement.getAttributeValue("redirect")));
        }
        if (jsElement != null) {
            appConfig.setInlineJs(jsElement.getTextTrim());
        }
        if(descElement != null) {
            appConfig.setDescription(descElement.getTextTrim());
        }
        if(ovlyElement != null) {
            appConfig.setOverlay(ovlyElement.getTextTrim());
        }
        if(dnElement != null) {
            appConfig.setDisplayName(dnElement.getTextTrim());
        }
        if(ijsElement != null) {
            for (Element element1 : ijsElement) {
                appConfig.addInjectjs(element1.getTextTrim());
            }
        }

        return appConfig;
    }

    private static Document getDOM() throws JDOMException, IOException {
        File configFile = getConfigFile();
        return new SAXBuilder().build(configFile);
    }

    private static File getConfigFile() throws IOException {
        String base = "./";
        new File(base).mkdirs();
        return new File(base + File.separator + "apps.xml");
    }

}
